/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.smn.jsf;

import com.smn.domain.MyUser;
import com.smn.domain.Ticket;
import com.smn.jsf.util.JsfUtil;
import java.io.Serializable;
import java.util.Date;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;

/**
 *
 * @author Ant Ongun Kefeli
 */
@ManagedBean(name = "spreadPageController")
@SessionScoped
public class SpreadPageController implements Serializable {

    @EJB
    private com.smn.dao.MyUserFacade ejbMyUserFacade;
    @EJB
    private com.smn.dao.TicketFacade ejbTicketFacade;
    @ManagedProperty(value = "#{myUserController}")
    private MyUserController myUserController;
    @ManagedProperty(value = "#{shareController}")
    private ShareController shareController;
    @ManagedProperty(value = "#{friendTableBean}")
    private FriendTableBean friendTableBean;

    public void setFriendTableBean(FriendTableBean friendTableBean) {
        this.friendTableBean = friendTableBean;
    }

    /** Creates a new instance of SpreadPageController */
    public SpreadPageController() {
    }

    public void setMyUserController(MyUserController myUserController) {
        this.myUserController = myUserController;
    }

    public void setShareController(ShareController shareController) {
        this.shareController = shareController;
    }

    public String createFriendAndTicket() {
        try {
            for (MyUser friend : friendTableBean.getFriends()) {


                if (friend.getUserName().equals("")) {
                    friend.setUserName(null);
                } else if (ejbMyUserFacade.findUser(friend.getUserName()) != null) {
                    friend = ejbMyUserFacade.findUser(friend.getUserName());
                } else {
                    ejbMyUserFacade.create(friend);
                }
                JsfUtil.addSuccessMessage(friend.getFirstName() + " " + friend.getLastName() + " is succesfully invited.");

                Ticket ticket = new Ticket();
                ticket.setOwner(myUserController.getCurrent());
                ticket.setReferer(friend);
                ticket.setShare(shareController.getSelected());
                ticket.setAccepted(false);
                ejbTicketFacade.create(ticket);
                friend = null;

            }

            friendTableBean.getFriends().clear();
            friendTableBean.enlargeList();
            shareController.prepareCreate();
            return "spread";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, "Error inviting!!!\n" + e.getLocalizedMessage());
            return null;
        }

    }
}
